package com.nineclock.attendance.task;

import com.nineclock.attendance.mapper.AttendGroupMapper;
import com.nineclock.attendance.pojo.AttendGroup;
import com.nineclock.attendance.service.AttendPunchService;
import com.nineclock.system.dto.SysCompanyUserDTO;
import com.nineclock.system.feign.SysCompanyUserFeign;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 定时生成考勤报表，并发送邮件
 */
@Component
@Slf4j
public class SendAttendMailTask {

    @Autowired
    private AttendGroupMapper attendGroupMapper;

    @Autowired
    private AttendPunchService attendPunchService;

    @Autowired
    private SysCompanyUserFeign companyUserFeign;

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;

    @XxlJob("countAttendanceAndSendMail")
    public void countAttendanceAndSendMail(){

        try {
            log.info("----开始执行定时调度，生成考勤报表，并发送给企业管理员");

            // 1.获取设置了考勤组的企业id集合
            Set<Long> companyIds = queryAllCompanyIds();

            // 2.遍历企业id，分别生成考勤报表，并发送邮件
            if(!CollectionUtils.isEmpty(companyIds)){

                for (Long companyId : companyIds) {

                    // 2.1 生成该企业的考勤报表
                    String excelPath = attendPunchService.generatePunchReport(companyId);

                    // 2.2 获取企业的主管理员信息
                    SysCompanyUserDTO admin = companyUserFeign.queryAdminByCompanyId(companyId).getData();

                    // 2.3 给企业管理员发送邮件
                    if(admin != null && !StringUtils.isEmpty(admin.getEmail())){
                        // 发送邮件
                        sendMail(admin, excelPath);
                    }
                }
            }
        } catch (Exception e) {
           log.error("定时任务出错：", e);
        }

    }

    /**
     * 给企业管理员发送邮件
     * @param admin
     * @param excelPath
     */
    private void sendMail(SysCompanyUserDTO admin, String excelPath) throws Exception{
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);

        messageHelper.setFrom(from);
        messageHelper.setTo(admin.getEmail()); // 收件人邮箱，主管理员的邮箱
        messageHelper.setSubject("考勤数据报表");
        messageHelper.setText("您好, 本月考勤数据报表已经生成, 请查收附件, 谢谢");

        messageHelper.addAttachment("本月考勤数据.xls", new File(excelPath));

        javaMailSender.send(mimeMessage);
    }

    /**
     * 获取设置了考勤组的企业id集合
     */
    private Set<Long> queryAllCompanyIds() {
        List<AttendGroup> attendGroupList = attendGroupMapper.selectList(null);
        
        // 获取数据中的企业id并且去重
        if(!CollectionUtils.isEmpty(attendGroupList)){

            Set<Long> companyIds = attendGroupList.stream().map(attendGroup -> {
                return attendGroup.getCompanyId();
            }).collect(Collectors.toSet());

            return companyIds;
        }

        return null;
    }


}
